package com.wecloud.core.server;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.wecloud.core.constant.ErrorMsg;
import com.wecloud.core.constant.WeContext;
import com.wecloud.core.exception.WeException;
@Component
public class UploadFilesServer {
	public static final String URL = "/file/";
	Logger log = LoggerFactory.getLogger(UploadFilesServer.class);
	@Async("uploadAsync")
	public Future execute(WeContext context) throws UnsupportedEncodingException {
		MultipartHttpServletRequest req = (MultipartHttpServletRequest) context.getRequest();
		context.getRequest().setCharacterEncoding("UTF-8");
		List<MultipartFile> files = req.getFiles("fileName");
		String path = java.net.URLDecoder.decode(URL + context.getUser().getUserId() + "/resources/", "UTF-8");//文件存放路径
		FileOutputStream fileOutput = null;
		List list = new ArrayList();
		if(files != null && files.size() > 0){
			for (MultipartFile file : files) {
				if (!new File(path).exists()) {
					new File(path).mkdirs();
				}
				try {
					fileOutput = new FileOutputStream(path + file.getOriginalFilename());
					log.error("#######################################"+file.getOriginalFilename()+"##########################");
					fileOutput.write(file.getBytes());
					fileOutput.flush();
					Map map = new HashMap();
					map.put("filename", file.getOriginalFilename());
					map.put("path", path);
					list.add(map);
				} catch (FileNotFoundException e) {
					throw new WeException(ErrorMsg.Error_9999);
				} catch (IOException e) {
					throw new WeException(ErrorMsg.Error_9999);
				}finally{
					try {
						fileOutput.close();
					} catch (IOException e) {
						throw new WeException(ErrorMsg.Error_9999);
					}
				}
			}
		}
		return new AsyncResult(list);
	}
}
